package org.example.java.util.concurrency.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import sun.misc.Unsafe;

/**
 * @author juntao zhang
 */
public class ReentrantLockTest {
  private static final Unsafe unsafe = Unsafe.getUnsafe();

  Lock lock = new ReentrantLock(false);
//  private static final long valueOffset;
//  private volatile int value;
//
//  static {
//    try {
//      valueOffset = unsafe.objectFieldOffset
//          (AtomicInteger.class.getDeclaredField("value"));
//    } catch (Exception ex) { throw new Error(ex); }
//  }

  void test() {
    lock.lock();
    try {
//      Thread.interrupted();
      Thread.sleep(100);
    } catch (InterruptedException e) {
      System.out.println("===");
      e.printStackTrace();
    } finally {
      lock.unlock();
      System.out.println(Thread.currentThread().getName() + " unlock");
    }
  }

  public static void main(String[] args) {
    ReentrantLockTest t = new ReentrantLockTest();
    int i = 0;
    Thread[] threads = new Thread[20];
    while (i < 20) {
      threads[i] = new Thread(t::test);
      threads[i].start();
      i++;
    }
    threads[10].interrupt();

//     unsafe.getAndSetInt(t, valueOffset, 1);


  }
}
